<template>
  <LoginFormTitle v-show="getShow" class="enter-x" />
  <Form
    class="p-4 enter-x"
    :model="formData"
    :rules="getFormRules"
    ref="formRef"
    v-show="getShow"
    @keypress.enter="handleLogin"
  >
    <FormItem name="account" class="enter-x">
      <Input
        size="large"
        v-model:value="formData.account"
        :placeholder="t('sys.login.userName')"
        class="fix-auto-fill"
      />
    </FormItem>
    <FormItem name="password" class="enter-x">
      <InputPassword
        size="large"
        visibilityToggle
        v-model:value="formData.password"
        :placeholder="t('sys.login.password')"
      />
    </FormItem>

    <div style="display: flex; gap: 12px; align-items: center">
      <FormItem layout="inline" class="enter-x">
        <Input
          size="large"
          v-model:value="formData.code"
          placeholder="验证码"
          class="fix-auto-fill"
        />
      </FormItem>

      <FormItem layout="inline" class="enter-x">
        <Image :src="codeImg" :preview="false" @click="getCode" />
      </FormItem>
    </div>

    <FormItem name="google" class="enter-x">
      <Input size="large" v-model:value="formData.google" placeholder="Gooogle验证码（未绑定不用输入）" />
    </FormItem>

    <ARow class="enter-x">
      <ACol :span="12">
        <FormItem>
          <!-- No logic, you need to deal with it yourself -->
          <Checkbox v-model:checked="formData.keep" size="small">
            {{ t('sys.login.rememberMe') }}
          </Checkbox>
        </FormItem>
      </ACol>
    </ARow>

    <FormItem class="enter-x">
      <Button type="primary" size="large" block @click="handleLogin" :loading="loading">
        {{ t('sys.login.loginButton') }}
      </Button>
      <!-- <Button size="large" class="mt-4 enter-x" block @click="handleRegister">
        {{ t('sys.login.registerButton') }}
      </Button> -->
    </FormItem>
  </Form>
</template>
<script lang="ts" setup>
  import { reactive, ref, unref, computed, onMounted } from 'vue';

  import { Checkbox, Form, Input, Row, Col, Button, Image } from 'ant-design-vue';

  import LoginFormTitle from './LoginFormTitle.vue';

  import { useI18n } from '@/hooks/web/useI18n';
  import { useMessage } from '@/hooks/web/useMessage';

  import { useUserStore } from '@/store/modules/user';
  import { LoginStateEnum, useLoginState, useFormRules, useFormValid } from './useLogin';
  import { useDesign } from '@/hooks/web/useDesign';

  import { useRoute } from 'vue-router';
  import { GetCodeApi } from '@/api/user';
  //import { onKeyStroke } from '@vueuse/core';

  const ACol = Col;
  const ARow = Row;
  const FormItem = Form.Item;
  const InputPassword = Input.Password;
  const { t } = useI18n();
  const { notification, createErrorModal, createWarningModal } = useMessage();
  const { prefixCls } = useDesign('login');
  const userStore = useUserStore();

  const { getLoginState } = useLoginState();
  const { getFormRules } = useFormRules();

  const formRef = ref();
  const loading = ref(false);
  const route = useRoute();
  const codeImg = ref();

  const formData = reactive({
    account: '',
    password: '',
    keep: false,
    google: '',
    code: '',
  });

  const { validForm } = useFormValid(formRef);

  //onKeyStroke('Enter', handleLogin);

  const getShow = computed(() => unref(getLoginState) === LoginStateEnum.LOGIN);
  const showGoogle = ref(false);

  onMounted(async () => {
    const virtualToken = route.query.virtualToken as string;
    if (virtualToken) {
      const userInfo = await userStore.xnLogin(virtualToken);
      notification.success({
        message: t('sys.login.loginSuccessTitle'),
        description: `${t('sys.login.loginSuccessDesc')}: ${userInfo.nickname}`,
        duration: 3,
      });
    }
    getCode();
  });
  async function handleLogin() {
    const data = await validForm();
    if (!data) return;
    try {
      loading.value = true;
      const userInfo = await userStore.login({
        password: formData.password,
        username: formData.account,
        keep: formData.keep ? '1' : '0',
        google: formData.google,
        code: formData.code,
        mode: 'none', //不要默认的错误提示
      });
      if (userInfo?.code === 201) {
        showGoogle.value = true;
        createWarningModal({
          title: '登录失败',
          content: userInfo?.msg,
          getContainer: () => document.body.querySelector(`.${prefixCls}`) || document.body,
        });
        return;
      }
      if (userInfo) {
        notification.success({
          message: t('sys.login.loginSuccessTitle'),
          description: `${t('sys.login.loginSuccessDesc')}: ${userInfo.nickname}`,
          duration: 3,
        });
      }
    } catch (error) {
      createErrorModal({
        title: t('sys.api.errorTip'),
        content: (error as unknown as Error).message || t('sys.api.networkExceptionMsg'),
        getContainer: () => document.body.querySelector(`.${prefixCls}`) || document.body,
      });
    } finally {
      loading.value = false;
    }
  }

  async function getCode() {
    const url = await GetCodeApi();
    codeImg.value = url;
  }
</script>
